//
//  YZAudioRecordVC.m
//  VET
//
//  Created by 刘文靖 on 2018/7/13.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZAudioRecordVC.h"
#import "YZRecordManager.h"
#import "YZPopupController.h"
#import "YZPopupCustomView.h"
@interface YZAudioRecordVC ()
@property (nonatomic, strong) UILabel *countDownLabel ;
@property (nonatomic, strong) UIButton *saveBtn;
@property (nonatomic, strong) UIButton *recordBtn;
@property (nonatomic, strong) UILabel *recordLabel ;
@property (nonatomic, weak) NSTimer *countdownTimer;
@property (nonatomic, assign) NSInteger countdownInterval;
@property (nonatomic, strong) NSString *recordPath;
@property (nonatomic, assign) NSInteger millisecond;
@property (nonatomic, strong) UIButton *pauseBtn;
@property (nonatomic, strong) UIButton *recordBackBtn;
@property (nonatomic, strong) UIButton *recordDeleteBtn;
@property (nonatomic, strong) UILabel *continueLabel;
@property (nonatomic, strong) UIView *reordingView;
@property (nonatomic, strong) UIView *animationView;
@property (nonatomic,strong) CAReplicatorLayer *replicatorLayer;
@end

#define recordName @"workNoteRecord"
@implementation YZAudioRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupMainView];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)setupMainView{
    self.view.backgroundColor = kColorWithHex(0x2E2B3D);
    UIView *topToolBar = [[UIView alloc]initWithFrame:CGRectMake(0, 10 + kStatusBarHeight, kScreenWidth, 25)];
    [self.view addSubview:topToolBar];
    UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(14, 4, 16, 16)];
    [closeBtn setBackgroundImage:[UIImage imageNamed:@"record_back"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(dismissViewController) forControlEvents:UIControlEventTouchUpInside];
    [topToolBar addSubview:closeBtn];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
    titleLabel.textColor = kColorWithHex(0xffffff);
    titleLabel.size = CGSizeMake(80, 25);
    titleLabel.top = 0;
    titleLabel.centerX = topToolBar.centerX;
    titleLabel.text = @"语音存档";
    [topToolBar addSubview:titleLabel];
    UIButton *saveBtn = [[UIButton alloc] init];
    saveBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
    saveBtn.size = CGSizeMake(41, 25);
    saveBtn.top = 0;
    saveBtn.right = kScreenWidth  - 17;
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:kColorWithHex(0x32BE60) forState:UIControlStateNormal];
    [saveBtn setTitleColor:kColorWithHexAlpha(0xFFFFFF, 0.5) forState:UIControlStateDisabled];
    saveBtn.enabled = NO;
    [topToolBar addSubview:saveBtn];
    self.saveBtn = saveBtn;
    
    self.countDownLabel = [[UILabel alloc] init];
    self.countDownLabel.textAlignment = NSTextAlignmentCenter;
    self.countDownLabel.textColor = kColorWithHex(0x32BE60);
    self.countDownLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:40];
    self.countDownLabel.text = @"00:00.00";
    [self.view addSubview:self.countDownLabel];
    [self.countDownLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.size.mas_equalTo(CGSizeMake(167, 48));
        make.top.mas_equalTo(topToolBar.mas_bottom).offset(123);
        
    }];
    
    self.reordingView = [[UIView alloc] init];
    self.reordingView.hidden = YES;
    [self.view addSubview:self.reordingView];
    [self.reordingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.countDownLabel.mas_bottom).offset(17);
        make.width.mas_equalTo(61);
        make.centerX.offset(0);
    }];
    
    UIImageView *recordingIV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"record_micro"]];
    [self.reordingView addSubview:recordingIV];
    [recordingIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.centerX.offset(0);
    }];
    
    UILabel *recordingLabel = [[UILabel alloc] init];
    recordingLabel.textColor = kColorWithHex(0x32BE60);
    recordingLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    recordingLabel.text = @"录音中 …";
    [self.reordingView addSubview:recordingLabel];
    [recordingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(recordingIV.mas_bottom).offset(5);
        make.height.mas_equalTo(20);
        make.left.right.bottom.offset(0);
    }];
    
    self.recordBtn = [[UIButton alloc] init];
    [self.recordBtn setBackgroundImage:[UIImage imageNamed:@"record_start"] forState:UIControlStateNormal];
    [self.view addSubview:self.recordBtn];
    [self.recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-93);
        make.centerX.offset(0);
    }];
    
    self.animationView = [[UIView alloc] init];
    self.animationView.backgroundColor = [UIColor clearColor];
    [self.view insertSubview:self.animationView belowSubview:self.recordBtn];
    [self.animationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.mas_equalTo(self.reordingView.mas_bottom).offset(18);
    }];
    
    self.pauseBtn = [[UIButton alloc] init];
    [self.pauseBtn setBackgroundImage:[UIImage imageNamed:@"record_pause"] forState:UIControlStateNormal];
    [self.pauseBtn setBackgroundImage:[UIImage imageNamed:@"record_continue"] forState:UIControlStateSelected];
    [self.view addSubview:self.pauseBtn];
    [self.pauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.animationView);
        make.centerX.offset(0);
    }];
    self.pauseBtn.hidden = YES;
    
    self.continueLabel = [[UILabel alloc] init];
    self.continueLabel.textAlignment = NSTextAlignmentCenter;
    self.continueLabel.text = @"点击继续录音";
    self.continueLabel.textColor = kColorWithHex(0x32BE60);
    self.continueLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12];
    [self.view addSubview:self.continueLabel];
    [self.continueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.pauseBtn.mas_bottom).offset(12);
        make.left.right.mas_equalTo(self.pauseBtn);
    }];
    self.continueLabel.hidden = YES;
    
    self.recordBackBtn = [[UIButton alloc] init];
    [self.recordBackBtn setBackgroundImage:[UIImage imageNamed:@"ass_btn_camera_black"] forState:UIControlStateNormal];
    [self.view addSubview:self.recordBackBtn];
    [self.recordBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.pauseBtn.mas_left).offset(-38);
        make.centerY.mas_equalTo(self.pauseBtn);
    }];
    self.recordBackBtn.hidden = YES;
    self.recordBackBtn.transform = CGAffineTransformMakeTranslation(120, 0);
    
    self.recordDeleteBtn = [[UIButton alloc] init];
    [self.recordDeleteBtn setBackgroundImage:[UIImage imageNamed:@"record_deleteBackground"] forState:UIControlStateNormal];
    [self.recordDeleteBtn setImage:[UIImage imageNamed:@"record_delete"] forState:UIControlStateNormal];
    [self.view addSubview:self.recordDeleteBtn];
    [self.recordDeleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.pauseBtn.mas_right).offset(38);
        make.centerY.mas_equalTo(self.pauseBtn);
    }];
    self.recordDeleteBtn.hidden = YES;
    self.recordDeleteBtn.transform = CGAffineTransformMakeTranslation(-120, 0);
    
    self.recordLabel = [[UILabel alloc] init];
    self.recordLabel.textAlignment = NSTextAlignmentCenter;
    self.recordLabel.textColor = kColorWithHexAlpha(0xFFFFFF, 0.5);
    self.recordLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    self.recordLabel.text = @"点击录音";
    [self.view addSubview:self.recordLabel];
    [self.recordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.mas_equalTo(self.recordBtn.mas_bottom).offset(5);
    }];
    @weakify(self)
    [[self.recordBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        self.reordingView.hidden = NO;
        [self startRecord];
    }];
    [[self.saveBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self stopRecord];
    }];
    
    [[self.pauseBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        self.pauseBtn.selected = !self.pauseBtn.selected;
        if (self.pauseBtn.selected) {
            [self pauseRecord];
            [UIView animateWithDuration:0.2 animations:^{
                self.recordDeleteBtn.transform = CGAffineTransformIdentity;
            }];
            
            [UIView animateWithDuration:0.2 animations:^{
                self.recordBackBtn.transform = CGAffineTransformIdentity;
            }];
        }else{
            [self continueRecord];
            [UIView animateWithDuration:0.2 animations:^{
                self.recordBackBtn.transform = CGAffineTransformMakeTranslation(120, 0);
                self.recordBackBtn.alpha = 0.1;
            }completion:^(BOOL finished) {
                self.recordBackBtn.hidden = YES;
                self.recordBackBtn.alpha = 1;
            }];
            
            [UIView animateWithDuration:0.2 animations:^{
                self.recordDeleteBtn.transform = CGAffineTransformMakeTranslation(-120, 0);
                self.recordDeleteBtn.alpha = 0.1;
            } completion:^(BOOL finished) {
                self.recordDeleteBtn.hidden = YES;
                self.recordDeleteBtn.alpha = 1;
            }];
        }
    }];
    
    [[self.recordBackBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self dismissViewController];
    }];
    
    [[self.recordDeleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
        @weakify(self)
        [customView setupUIWithTitle:nil message:@"确定要删除当前录音?" confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
            @strongify(self)
            [self.YZ_popupController dismiss];
            self.continueLabel.hidden = YES;
            self.saveBtn.enabled = NO;
            self.pauseBtn.hidden = YES;
            self.recordDeleteBtn.hidden = YES;
            self.recordBackBtn.hidden = YES;
            self.recordBtn.hidden = NO;
            self.millisecond = 0;
            self.countDownLabel.text = @"00:00.00";
        } cancelHandler:^{
            [self.YZ_popupController dismiss];
        }];
        [self.YZ_popupController presentContentView:customView];
    }];
    
}

- (void)startRecord{
    self.recordLabel.hidden = YES;
    self.recordBtn.hidden = YES;
    self.pauseBtn.hidden = NO;
    [self addAnimation];
    @weakify(self)
    [[YZRecordManager shareManager] startRecordWithFileName:recordName completion:^(NSError *error) {
        @strongify(self)
        if (!error) {
            [self setupCountdownTimer];
        }
    }];
}

- (void)stopRecord{
    @weakify(self)
    [[YZRecordManager shareManager] stopRecordCompletion:^(NSString *finish) {
        @strongify(self)
        if ([finish isEqualToString:shortRecord]) {//录制时间太短
            [[YZRecordManager shareManager] removeCurrentRecordFile:recordName];
        } else{
            self.recordPath = finish;
            if (self.recordSuccessBlock) {
                self.recordSuccessBlock(self.recordPath,self.countdownInterval);
            }
            [self dismissViewController];
        }
    }];
}

- (void)pauseRecord{
    self.saveBtn.enabled = YES;
    self.reordingView.hidden = YES;
    self.continueLabel.hidden = NO;
    self.recordDeleteBtn.hidden = NO;
    self.recordBackBtn.hidden = NO;
    [self.replicatorLayer removeFromSuperlayer];
    self.replicatorLayer = nil;
    [self releaseCountdownTimer];
    [[YZRecordManager shareManager] pauseRecord];
}

- (void)continueRecord{
    self.saveBtn.enabled = NO;
    self.reordingView.hidden = NO;
    self.continueLabel.hidden = YES;
    [self addAnimation];
    [self setupCountdownTimer];
    [[YZRecordManager shareManager] resumeRecord];
}

- (void)dismissViewController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)setupCountdownTimer {
    [self releaseCountdownTimer];
    self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.countdownTimer forMode:NSRunLoopCommonModes];
}

- (void)releaseCountdownTimer {
    [self.countdownTimer invalidate];
}

- (void)updateCountdown{
    ++self.millisecond;
    self.countdownInterval = self.millisecond / 100;
    if (self.countdownInterval <= 180) {
        NSInteger minutes = self.countdownInterval / 60;
        NSInteger seconds = self.countdownInterval % 60;
        NSInteger millisecond = self.millisecond % 100;
        NSString *secondStr = seconds >= 10 ? [NSString stringWithFormat:@"%ld",seconds]:[NSString stringWithFormat:@"0%ld",seconds];
        NSString *millisecondStr = millisecond >= 10 ? [NSString stringWithFormat:@"%ld",millisecond]:[NSString stringWithFormat:@"0%ld",millisecond];
        self.countDownLabel.text = [NSString stringWithFormat:@"0%ld:%@.%@",(long)minutes,secondStr,millisecondStr];
    }else{
        [self releaseCountdownTimer];
    }
}

- (void)addAnimation
{
    //CAShapeLayer和CAReplicatorLayer都是CALayer的子类
    //CAShapeLayer的实现必须有一个path，可以配合贝塞尔曲线
    CAShapeLayer *pulseLayer = [CAShapeLayer layer];
    pulseLayer.frame = _animationView.layer.bounds;
    pulseLayer.path = [UIBezierPath bezierPathWithOvalInRect:pulseLayer.bounds].CGPath;
    pulseLayer.lineWidth = 5;
    pulseLayer.fillColor = kColorWithHex(0x353343).CGColor;//填充色
    pulseLayer.strokeColor = kColorWithHexAlpha(0xffffff, 0.5).CGColor;//描边色
    pulseLayer.opacity = 0.0;
    
    //可以复制layer
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    replicatorLayer.frame = _animationView.bounds;
    replicatorLayer.instanceCount = 4;//创建副本的数量,包括源对象。
    replicatorLayer.instanceDelay = 0.5;//复制副本之间的延迟
    [replicatorLayer addSublayer:pulseLayer];
    [_animationView.layer addSublayer:replicatorLayer];
    self.replicatorLayer = replicatorLayer;
    
    CABasicAnimation *opacityAnima = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnima.fromValue = @(0.3);
    opacityAnima.toValue = @(0.0);
    
    CABasicAnimation *scaleAnima = [CABasicAnimation animationWithKeyPath:@"transform"];
    scaleAnima.fromValue = [NSValue valueWithCATransform3D:CATransform3DScale(CATransform3DIdentity, 0.0, 0.0, 0.0)];
    scaleAnima.toValue = [NSValue valueWithCATransform3D:CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 0.0)];
    
    CAAnimationGroup *groupAnima = [CAAnimationGroup animation];
    groupAnima.animations = @[opacityAnima, scaleAnima];
    groupAnima.duration = 2.0;
    groupAnima.autoreverses = NO;
    groupAnima.repeatCount = HUGE;
    
    [pulseLayer addAnimation:groupAnima forKey:@"groupAnimation"];
    
}

@end
